﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// WMM_TMS出库信息回写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WMStoTMSAddShipInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_wms_zh;
        public readonly string con_wms_qh;
        public readonly string con_wms_sc;
        public readonly string con_erp;
        public readonly string con_wms_gd;
        public readonly string con_wms_gz;
        public readonly string con_wms_fl;


        public WMStoTMSAddShipInfoController(ILogger<WMStoTMSAddShipInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_wms_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_wms_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_wms_sc = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_erp = _configuration.GetConnectionString("ERP_DbConnection");
            con_wms_gd = _configuration.GetConnectionString("WMSDbConnection_GD");
            con_wms_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            con_wms_fl = _configuration.GetConnectionString("FL_DbConnection");
            _logger = loggerFactory.CreateLogger<WMStoTMSAddShipInfoController>();
        }

        /// <summary>
        /// WMM_TMS出库信息回写
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWMStoTMSAddShipInfo([FromBody] WMStoTMSAddShipInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMtoWMSAddCarInfoResponseDto re = new TMtoWMSAddCarInfoResponseDto();
            string waybill_no = strparm.waybill_no;
            string in_con = "";//目标WMS数据库
            try
            {
                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "factory_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_wms_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_wms_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_wms_sc;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {
                    dic = new Dictionary<string, string>(); //查询公用dic
                    dic.Add("waybill_no", waybill_no);//查询对应物流计划
                    DataTable tms_wj = MethodHelp.GetTableInfo("TMS0074", dic, con);//获取物流发运单明细，外键ID信息
                    if (tms_wj.Rows.Count>0)
                    {
                        dic = new Dictionary<string, string>();
                        dic.Add("waybill_no", waybill_no);
                        string strsql1 = MethodHelp.GetTranSQL("TMS0078", dic, con);
                        if (strsql1 != "")
                        {
                            strSqlList.Add(strsql1.ToString());
                        }
                        else
                        {
                            strMsg = "Parameter conversion failed";
                        }

                        if (strMsg=="")
                        {
                                                      
                            if (strparm.factory_code.Contains("gz"))
                            {
                                dic = new Dictionary<string, string>();
                                dic.Add("waybill_no", waybill_no);
                                DataTable dt_rp = MethodHelp.GetTableInfo("TMS0093", dic, con);
                                if (dt_rp.Rows.Count <= 0)
                                {
                                    //签收明细插入
                                    foreach (DataRow row in tms_wj.Rows)
                                    {
                                        dic = new Dictionary<string, string>();
                                        //基础ID信息
                                        dic.Add("tab_doc_id", row["tab_doc_id"].ToString());
                                        dic.Add("status", row["status"].ToString());
                                        dic.Add("tenant_id", row["tenant_id"].ToString());
                                        dic.Add("form_id", row["form_id"].ToString());
                                        dic.Add("process_id", row["process_id"].ToString());
                                        dic.Add("owner", row["owner"].ToString());
                                        //业务数据
                                        dic.Add("waybill_no", row["waybill_no"].ToString());
                                        dic.Add("customer_name", row["customer_name"].ToString());
                                        dic.Add("delivery_address", row["delivery_address"].ToString());
                                        dic.Add("receipt_no", row["receipt_no"].ToString());
                                        dic.Add("qty", row["qty"].ToString());
                                        string strSQL = MethodHelp.GetTranSQL("TMS0076", dic, con);
                                        if (strSQL != "")
                                        {
                                            strSqlList.Add(strSQL.ToString());
                                        }
                                        else
                                        {
                                            strMsg = "Parameter conversion failed";
                                        }
                                    }
                                }

                                DataTable dt_type = MethodHelp.GetTableInfo("TMS0142", dic, con);//获取物流发运单，配送类型，委外推CRM，非委外推WMS
                                if (dt_type.Rows.Count>0)
                                {
                                    //代工取CRM外协挑库单出库数据
                                    if (dt_type.Rows[0]["business_type"].ToString() == "代工配送")
                                    {
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("shipment_no", waybill_no);//运单
                                        DataTable dt_wx_ck = MethodHelp.GetTableInfo("TMS0147", dic,con);
                                        if (dt_wx_ck.Rows.Count>0)
                                        {
                                            foreach (DataRow item in dt_wx_ck.Rows)
                                            {
                                                dic = new Dictionary<string, string>();
                                                //基础ID信息
                                                dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                                dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                                dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                                dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                                dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                                dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                                //业务数据
                                                dic.Add("waybill_no", item["shipment_no"].ToString());
                                                dic.Add("plan_no", item["plan_no_id"].ToString());
                                                dic.Add("customer_code", item["customer_code"].ToString());
                                                dic.Add("customer_name", item["customer_name"].ToString());
                                                dic.Add("saleorder_no", item["saleorder_no"].ToString());
                                                dic.Add("saleorderline_no", item["saleorderline_no"].ToString());
                                                dic.Add("material_code", item["material_code"].ToString());
                                                dic.Add("material_name", item["material_name"].ToString());
                                                dic.Add("qty", item["material_amount"].ToString());
                                                dic.Add("delivery_no", item["shipment_no"].ToString());
                                                string strSQL = MethodHelp.GetTranSQL("TMS0075", dic, con);
                                                if (strSQL != "")
                                                {
                                                    strSqlList.Add(strSQL.ToString());
                                                }
                                                else
                                                {
                                                    strMsg = "TMS0075 Parameter conversion failed";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            strMsg = "运单号=<" + waybill_no + "> 获取获取外协出库数据失败，请确认是否已出库!";
                                        }
                                        if (strMsg=="")
                                        {
                                            if (strSqlList.Count > 0)
                                            {
                                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                if (A)
                                                {

                                                }
                                                else
                                                {
                                                    strMsg = "TMS0075 Database update failed";
                                                }
                                            }
                                            else
                                            {
                                                strMsg = "TMS0075 No insertion data present";
                                            }
                                        }                                        
                                    }
                                    //取WMS库存出库数据
                                    else
                                    {
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                                        string strsql = MethodHelp.GetTranSQL("TMS0073", dic, con);//获取查询语句SQL
                                        if (strsql == "")
                                        {
                                            strMsg = "运单号=<" + waybill_no + "> 获取SQL语句失败，请找IT确认!";
                                        }
                                        else
                                        {
                                            //获取WMS查询视图
                                            DataTable dt_wms_details = DB.OracleQuery(strsql, con_wms_fl);//获取WMS发货数据
                                            if (dt_wms_details.Rows.Count > 0)
                                            {
                                                //出库明细回写
                                                foreach (DataRow item in dt_wms_details.Rows)
                                                {
                                                    dic = new Dictionary<string, string>();
                                                    //基础ID信息
                                                    dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                                    dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                                    dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                                    dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                                    dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                                    dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                                    //业务数据
                                                    dic.Add("waybill_no", item["TMSORDERNO"].ToString());
                                                    dic.Add("plan_no", item["DEDI06"].ToString());
                                                    dic.Add("customer_code", item["CONSIGNEEID"].ToString());
                                                    dic.Add("customer_name", item["CUSTOMERDESCR1"].ToString());
                                                    dic.Add("saleorder_no", item["SOREFERENCE1"].ToString());
                                                    dic.Add("saleorderline_no", item["REFLINENO"].ToString());
                                                    dic.Add("material_code", item["SKU"].ToString());
                                                    dic.Add("material_name", item["SKUDESCR1"].ToString());
                                                    dic.Add("qty", item["QTY"].ToString());
                                                    dic.Add("delivery_no", item["ORDERNO"].ToString());
                                                    string strSQL = MethodHelp.GetTranSQL("TMS0075", dic, con);
                                                    if (strSQL != "")
                                                    {
                                                        strSqlList.Add(strSQL.ToString());
                                                    }
                                                    else
                                                    {
                                                        strMsg = "Parameter conversion failed";
                                                    }
                                                }

                                            }
                                            else
                                            {
                                                //补偿表获取出库数据
                                                dic = new Dictionary<string, string>();
                                                dic.Add("waybill_no", waybill_no);
                                                DataTable bc_dt = MethodHelp.GetTableInfo("TMS0099", dic, con);
                                                if (bc_dt.Rows.Count > 0)
                                                {
                                                    foreach (DataRow rows in bc_dt.Rows)
                                                    {
                                                        dic = new Dictionary<string, string>();
                                                        //基础ID信息
                                                        dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                                        dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                                        dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                                        dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                                        dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                                        dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                                        //业务数据
                                                        dic.Add("waybill_no", waybill_no);
                                                        dic.Add("plan_no", "");
                                                        dic.Add("customer_code", rows["customer_code"].ToString());
                                                        dic.Add("customer_name", rows["customer_name"].ToString());
                                                        dic.Add("saleorder_no", rows["saleorder_no"].ToString());
                                                        dic.Add("saleorderline_no", rows["saleorderline_no"].ToString());
                                                        dic.Add("material_code", rows["material_code"].ToString());
                                                        dic.Add("material_name", rows["material_name"].ToString());
                                                        dic.Add("qty", rows["qty"].ToString());
                                                        dic.Add("delivery_no", rows["delivery_no"].ToString());
                                                        dic.Add("saleorderline_id", rows["saleorderline_no"].ToString());
                                                        dic.Add("end_custom", rows["customer_name"].ToString());
                                                        dic.Add("end_saleorderno", rows["end_salesorder"].ToString());
                                                        dic.Add("end_saleorderlineno", rows["end_orderlineno"].ToString());
                                                        dic.Add("delivery_address", rows["delivery_address"].ToString());
                                                        string strSQL = MethodHelp.GetTranSQL("TMS0096", dic, con);
                                                        if (strSQL != "")
                                                        {
                                                            strSqlList.Add(strSQL.ToString());
                                                        }
                                                        else
                                                        {
                                                            strMsg = "Parameter conversion failed";
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    strMsg = "组件运单号=<" + waybill_no + "> 获取WMS出库信息失败，请确认后再试!";
                                                }
                                            }

                                            if (strSqlList.Count > 0)
                                            {
                                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                if (A)
                                                {

                                                }
                                                else
                                                {
                                                    strMsg = "Database update failed";
                                                }
                                            }
                                            else
                                            {
                                                strMsg = "No insertion data present";
                                            }

                                        }
                                    }
                                }
                                else
                                {
                                    strMsg = "运单=<" + waybill_no + ">，TMS0142，获取不到业务类型 !";
                                }


                               
                            }
                            //晶硅WMS获取实际发货信息
                            else
                            {
                                dic = new Dictionary<string, string>(); //查询公用dic
                                dic.Add("shipping_order_no", waybill_no);//查询对应物流计划
                                DataTable dt_wms = MethodHelp.GetOutsideTableInfo("TMS0081", dic, in_con, con);//获取WMS出库信息
                                //DataTable dt_wms = MethodHelp.GetOutsideTableInfo("TMS0091", dic, in_con, con);//获取WMS出库信息
                                if (dt_wms.Rows.Count>0)
                                {
                                    //出库明细回写
                                    foreach (DataRow item in dt_wms.Rows)
                                    {
                                        dic = new Dictionary<string, string>();
                                        //基础ID信息
                                        dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                        dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                        dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                        dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                        dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                        dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                        //业务数据
                                        dic.Add("waybill_no", waybill_no);
                                        dic.Add("plan_no", "");
                                        dic.Add("customer_code", item["customer_code"].ToString());
                                        dic.Add("customer_name", item["customer_name"].ToString());
                                        dic.Add("saleorder_no", item["source_no"].ToString());
                                        dic.Add("saleorderline_no", item["n_lineno"].ToString());
                                        dic.Add("material_code", item["material_code"].ToString());
                                        dic.Add("material_name", item["material_name"].ToString());
                                        dic.Add("qty", item["material_amount"].ToString());
                                        dic.Add("delivery_no", item["waybill_no"].ToString());
                                        dic.Add("saleorderline_id", item["sales_order_line_id"].ToString());
                                        dic.Add("end_custom", item["final_custom"].ToString());
                                        dic.Add("end_saleorderno", item["ext_order_number"].ToString());
                                        dic.Add("end_saleorderlineno", item["w_lineno"].ToString());
                                        dic.Add("delivery_address", item["address"].ToString());
                                        //string strSQL = MethodHelp.GetTranSQL("TMS0075", dic, con);
                                        string strSQL = MethodHelp.GetTranSQL("TMS0096", dic, con);
                                        if (strSQL != "")
                                        {
                                            strSqlList.Add(strSQL.ToString());
                                        }
                                        else
                                        {
                                            strMsg = "Parameter conversion failed";
                                        }
                                    }

                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("shipping_order_no", waybill_no);//查询对应物流计划
                                    DataTable dt_wms_qs = MethodHelp.GetOutsideTableInfo("TMS0095", dic, in_con, con);
                                    if (dt_wms_qs.Rows.Count>0)
                                    {
                                        dic = new Dictionary<string, string>();
                                        dic.Add("waybill_no", waybill_no);
                                        DataTable dt_rp = MethodHelp.GetTableInfo("TMS0093", dic, con);
                                        if (dt_rp.Rows.Count <= 0)
                                        {
                                            foreach (DataRow item2 in dt_wms_qs.Rows)
                                            {
                                                dic = new Dictionary<string, string>();
                                                //基础ID信息
                                                dic.Add("tab_doc_id", tms_wj.Rows[0]["tab_doc_id"].ToString());
                                                dic.Add("status", tms_wj.Rows[0]["status"].ToString());
                                                dic.Add("tenant_id", tms_wj.Rows[0]["tenant_id"].ToString());
                                                dic.Add("form_id", tms_wj.Rows[0]["form_id"].ToString());
                                                dic.Add("process_id", tms_wj.Rows[0]["process_id"].ToString());
                                                dic.Add("owner", tms_wj.Rows[0]["owner"].ToString());
                                                //业务数据
                                                dic.Add("waybill_no", item2["shipping_order_no"].ToString());
                                                dic.Add("customer_name", item2["customer_name"].ToString());
                                                dic.Add("delivery_address", item2["address"].ToString());
                                                dic.Add("receipt_no", item2["receipt_no"].ToString());
                                                dic.Add("qty", item2["material_amount"].ToString());
                                                string strSQL = MethodHelp.GetTranSQL("TMS0076", dic, con);
                                                if (strSQL != "")
                                                {
                                                    strSqlList.Add(strSQL.ToString());
                                                }
                                                else
                                                {
                                                    strMsg = "Parameter conversion failed";
                                                }
                                            }
                                        }                                       
                                    }
                                }
                                else
                                {
                                    strMsg = "运单号=<" + waybill_no + "> 获取WMS出库信息失败，请确认后再试!";
                                }

                                if (strSqlList.Count > 0)
                                {
                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                    if (A)
                                    {

                                    }
                                    else
                                    {
                                        strMsg = "Database update failed";
                                    }
                                }
                                else
                                {
                                    strMsg = "No insertion data present";
                                }
                            }
                        }                       
                    }
                    else
                    {
                        strMsg = "运单号=<" + waybill_no + "> 获取订单明细失败，请确认后再试!";
                    }                                                               
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
